package server

import (
	"github.com/akirakazu/go-simplejson"
)

// "login" command handler
func (s *Server) onLogin(id string, m *Pack) {
	msg := json.New()
	// Check existence for "identity"
	if !m.Msg.Has("identity") {
		msg.Set("err", "identity missing")
		s.response(id, m, msg)
		return
	}

	// Check existence for "pwd"
	pwd, err := m.Msg.GetString("pwd")
	if err != nil {
		msg.Set("err", "pwd missing")
		s.response(id, m, msg)
		return
	}

	identity := m.Msg.Get("identity")

	// Auth
	if !s.auth(identity, pwd) {
		msg.Set("err", "wrong identity or password")
		s.response(id, m, msg)
		return
	}

	// Kick previous user with same identity offline
	if targetKey, ok := s.findConnWithoutSelfId(identity); ok {
		s.pb.closeConn(targetKey)
		delete(s.conns, targetKey)
	}

	// Create info
	conn := NewConn()
	conn.identity = identity
	s.conns[id] = conn

	// Response with ok
	msg.Set("msg", "ok")
	s.response(id, m, msg)

	// Publish CLIENT_LOGIN event
	subMsg := json.New()
	subMsg.Set("type", "CLIENT_LOGIN")
	subMsg.Set("client", identity)
	s.iterateListeners(subMsg)
}
